package com.wltt.product.frfront.config.javafx;

import com.wltt.product.frfront.config.exception.RobotException;
import com.wltt.product.frfront.config.javafx.utils.AlertUtil;
import com.wltt.product.frfront.holder.JavafxHolder;
import com.wltt.product.frfront.holder.RobotHolder;
import fairino.ROBOT_STATE_PKG;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.Background;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.util.Duration;
import org.controlsfx.control.MaskerPane;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class MainWindowsController implements Initializable {

    private static final String IPV4_PATTERN =
            "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";

    private int CurrentPage = 0;
    private WebView webView;
    private Node settingNode;
    private MaskerPane maskerPane;

    private boolean connetting = false;

    @FXML
    private TextField robotIpText;

    @FXML
    private Button connectButton;

    @FXML
    private Button switchRobotModelButton;

    @FXML
    private Button cleanErrorButton;

    @FXML
    private Label connectStatus;

    @FXML
    private Label modelStatusLabel;

    @FXML
    private TextField runStatusText;

    @FXML
    private StackPane contentPanel;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        robotIpText.setText(RobotHolder.getRobot().getRobotPO().getRobotIp());

        maskerPane = new MaskerPane();
        maskerPane.setVisible(false);

        contentPanel.setPadding(new Insets(0, 0, 0, 0));

        webView = new WebView();
        WebEngine webEngine = webView.getEngine();
//        try {
//            webEngine.setUserStyleSheetLocation(new ClassPathResource("css/light-theme.css").getURL().toExternalForm());
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        webEngine.setJavaScriptEnabled(true);
        webEngine.load("http://localhost:8090/");
        webView.setContextMenuEnabled(false);
        JavafxHolder.setWebView(webView);

        try {
            FXMLLoader fxmlLoader = new FXMLLoader(new ClassPathResource("javafx/setting.fxml").getURL());
            settingNode = fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }

        contentPanel.getChildren().addAll(webView, maskerPane);
        CurrentPage = 0;

        // 创建一个时间轴
        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(5), event -> {

            // 更新连接状态
            try {
                if (connetting) {
                    return;
                }

                if (RobotHolder.isRobotConnected()) {
                    connectStatus.setTextFill(Color.GREEN);
                    connectStatus.setText("已连接");
                    connectButton.setDisable(true);
                    robotIpText.setDisable(true);

                    ROBOT_STATE_PKG pkg = RobotHolder.getRobot().GetRobotRealTimeState();

                    // 更新机器人模式：手动、自动
                    updateRobotModelLabel(pkg);

                    // 更新运行状态
                    updateRunStatus(pkg);
                } else {
                    connectStatus.setTextFill(Color.RED);
                    connectStatus.setText("已断开");
                    connectButton.setDisable(false);
                    robotIpText.setDisable(false);

                    // 更新机器人模式：手动、自动
                    updateRobotModelLabel(null);

                    // 更新运行状态
                    updateRunStatus(null);
                }
            } catch (Exception e) {
            }
        }));
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
    }

    @FXML
    public void showWeld(ActionEvent actionEvent) {
        Platform.runLater(() -> {
            if (CurrentPage == 0) {
                return;
            }
            contentPanel.getChildren().set(0, webView);
            CurrentPage = 0;
        });
    }

    @FXML
    public void showSetting(ActionEvent actionEvent) {
        Platform.runLater(() -> {
            if (CurrentPage == 1) {
                return;
            }
            contentPanel.getChildren().set(0, settingNode);
            CurrentPage = 1;
        });
    }


    @FXML
    public void cleanError(ActionEvent actionEvent) {
        new Thread(() -> {
            try {
                maskerPane.setVisible(true);
                cleanErrorButton.setDisable(true);
                RobotHolder.getRobot().ResetAllError();
                RobotHolder.setIsError(false);
            } catch (RobotException e) {
                AlertUtil.alert(Alert.AlertType.ERROR, "错误", "清除错误信息失败", e.getMessage());
            } finally {
                maskerPane.setVisible(false);
                cleanErrorButton.setDisable(false);
            }
        }).start();
    }

    @FXML
    public void switchRobotModel(ActionEvent actionEvent) {
        new Thread(() -> {
            if (RobotHolder.getIsError()) {
                AlertUtil.alert(Alert.AlertType.WARNING, "警告", "存在异常信息", "请先清除当前机械臂的异常信息再尝试！");
            }
            try {
                maskerPane.setVisible(true);
                switchRobotModelButton.setDisable(true);
                if (RobotHolder.ROBOT_MODEL_STATUS == 0) {
                    RobotHolder.getRobot().Mode(1);
                    Platform.runLater(() -> modelStatusLabel.setText("手动"));
                } else {
                    RobotHolder.getRobot().Mode(0);
                    Platform.runLater(() -> modelStatusLabel.setText("自动"));
                }
            } catch (RobotException e) {
                AlertUtil.alert(Alert.AlertType.ERROR, "错误", "切换模式失败", e.getMessage());
            } finally {
                maskerPane.setVisible(false);
                switchRobotModelButton.setDisable(false);
            }
        }).start();
    }

    @FXML
    public void connectToRobot(ActionEvent actionEvent) {

        new Thread(() -> {
            try {
                connetting = true;
                maskerPane.setVisible(true);
                connectButton.setDisable(true);
                String robotIp = robotIpText.getText();
                if (robotIp == null || robotIp.equals("")) {
                    AlertUtil.alert(Alert.AlertType.ERROR, "错误", "无法连接机器人", "ip地址不能为空");
                    return;
                }
                if (!robotIp.matches(IPV4_PATTERN)) {
                    AlertUtil.alert(Alert.AlertType.ERROR, "错误", "无法连接机器人", "请输入正确的ip地址");
                    return;
                }
                boolean result = RobotHolder.getRobot().connectToRobot(robotIp);
                if (!result) {
                    AlertUtil.alert(Alert.AlertType.ERROR, "错误", "无法连接机器人", "请检查机器人是否开启，及网络是否联通！");
                    return;
                }
                RobotHolder.getRobot().getRobotPO().setRobotIp(robotIp);
                RobotHolder.getRobot().save();
                RobotHolder.setRobotIp(robotIp);
            } catch (RobotException e) {
                AlertUtil.alert(Alert.AlertType.ERROR, "错误", "初始机器人发生错误", "存在不可清除的错误信息！");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connetting = false;
                maskerPane.setVisible(false);
                connectButton.setDisable(false);
            }
        }).start();
    }

    private void updateRobotModelLabel(ROBOT_STATE_PKG pkg) {
        try {
            if (null == pkg) {
                modelStatusLabel.setText("--");
                return;
            }

            if (pkg.robot_mode == 0) {
                RobotHolder.ROBOT_MODEL_STATUS = 0;
                modelStatusLabel.setText("自动");
            } else  {
                RobotHolder.ROBOT_MODEL_STATUS = 1;
                modelStatusLabel.setText("手动");
            }
        } catch (Exception e) {
        }
    }

    private void updateRunStatus(ROBOT_STATE_PKG pkg) {
        if (null == pkg) {
            runStatusText.setText("--");
            RobotHolder.setIsError(false);
            return;
        }
        try {
            if (pkg.main_code == 0) {
                runStatusText.setBackground(Background.fill(Color.GREEN));
                runStatusText.setText("运行正常");
                RobotHolder.setIsError(false);
            } else {
                String errorMsg =  RobotHolder.getErrorMessage(pkg.sub_code, pkg.main_code);
                runStatusText.setBackground(Background.fill(Color.RED));
                runStatusText.setText(errorMsg);
                RobotHolder.setIsError(true);
            }
        } catch (Exception e) {
        }
    }
}